import React, { useCallback, useEffect, useRef, useState } from 'react';
import ReactDOM from 'react-dom';
import { Rnd } from 'react-rnd';
import { Card, Button, Select, Space } from 'antd';
import {
    CloseOutlined,
    FullscreenOutlined,
    PauseOutlined,
    AppstoreOutlined
} from '@ant-design/icons';
import './index.less';
import useHikCameraPlayer from '@/hooks/hikCamera/useHikCameraPlayer';

// 布局选项
const LAYOUT_OPTIONS = [
    { value: 1, label: '单窗口 (1×1)' },
    { value: 2, label: '四窗口 (2×2)' },
    { value: 3, label: '九窗口 (3×3)' },
    { value: 4, label: '十六窗口 (4×4)' }
];

const playerConfig = {
    width: 800,
    height: 600,
    minWidth: 600,
    minHeight: 400
}

const GlobalHikCameraPlayer: React.FC = () => {
    const playerRef = useRef<any>(null);
    const [layout, setLayout] = useState(LAYOUT_OPTIONS[1].value);

    const { state, setPlayer, setSelectedIndex, togglePlayer,
        setAllFullScreen, setSelectedWindowFullScreen, stopPlay, stopAllPlay, changeLayout,
    } = useHikCameraPlayer();

    const playerContainerRef = useRef<HTMLDivElement>(null);
    const [position, setPosition] = useState({
        x: (window.innerWidth - playerConfig.width + 100) / 2,
        y: (window.innerHeight - playerConfig.height) / 2
    });
    const [size, setSize] = useState({ width: playerConfig.width, height: playerConfig.height });

    useEffect(() => {
        if (state.visible) {
            initVideoPlayer();
        } else {
            destroyPlayer();
            setPlayer(null);
        }
    }, [state.visible]);

    // 处理窗口大小变化
    const handleResize = useCallback((_e: any, _direction: any, ref: HTMLElement, _delta: any, position: any) => {
        setSize({
            width: ref.offsetWidth,
            height: ref.offsetHeight
        });
        setPosition(position);
    }, []);

    // 处理拖动停止
    const handleDragStop = useCallback((_e: any, d: any) => {
        setPosition({ x: d.x, y: d.y });
    }, []);

    // 处理拖动开始
    const handleDragStart = useCallback(() => {
    }, []);

    const initVideoPlayer = () => {
        if (!playerContainerRef.current || !window.JSPlugin) return;

        const player = new window.JSPlugin({
            szId: 'multi_hik_camera_player',//父窗口id，需要英文字母开头 必填
            szBasePath: "./",// 必填,与h5player.min.js的引用路径一致
            iMaxSplit: 4,
            iCurrentSplit: 2,
            mseWorkerEnable: true,//是否开启多线程解码，分辨率大于1080P建议开启，否则可能卡顿
            bSupporDoubleClickFull: true,//是否支持双击全屏，true-双击是全屏；false-双击无响应
            oStyle: {
                borderSelect: '#FFCC00',
            }
        })
        playerRef.current = player;
        setPlayer(player);
        player.JS_SetWindowControlCallback({
            windowEventSelect: (iWndIndex: number) => {  //插件选中窗口回调
                setSelectedIndex(iWndIndex);
            }
        });
    }

    const destroyPlayer = () => {
        if (playerRef.current) {
            playerRef.current.JS_StopRealPlayAll();
            playerRef.current = null;
            setPlayer(null);
        }
    }

    const changeLayoutFn = (value: number) => {
        setLayout(value);
        changeLayout(value);
    }

    if (!state.visible) return null;

    const content = (
        <Rnd
            position={position}
            size={size}
            minWidth={playerConfig.minWidth}
            minHeight={playerConfig.minHeight}
            bounds="window"
            style={{ zIndex: 99, position: 'fixed' }}
            dragHandleClassName="player-header"
            onDragStart={handleDragStart}
            onDragStop={handleDragStop}
            onResizeStop={handleResize}
        >
            <Card
                className="player-container"
                style={{ width: '100%', height: '100%', display: 'flex', flexDirection: 'column' }}
                title={
                    <div className="player-header">
                        <Space size="middle">
                            <AppstoreOutlined className="header-icon" />
                            <span className="header-title">多窗口视频监控</span>
                            <Select
                                value={layout}
                                onChange={changeLayoutFn}
                                style={{ width: 140 }}
                                options={LAYOUT_OPTIONS}
                            />
                        </Space>
                    </div>
                }
                extra={
                    <Space className="player-actions" size="small" split={<span className="action-divider">|</span>}>
                        <Space size="small">
                            <Button
                                icon={<PauseOutlined />}
                                onClick={stopPlay}
                                disabled={true}
                                size="small"
                            >
                                停止当前
                            </Button>
                            <Button
                                icon={<PauseOutlined />}
                                onClick={stopAllPlay}
                                danger
                                size="small"
                            >
                                停止所有
                            </Button>
                        </Space>
                        <Space size="small">
                            <Button
                                icon={<FullscreenOutlined />}
                                onClick={() => {
                                    setSelectedWindowFullScreen();
                                }}
                                size="small"
                            >
                                单窗口全屏
                            </Button>
                            <Button
                                icon={<FullscreenOutlined />}
                                onClick={() => {
                                    setAllFullScreen(true);
                                }}
                                size="small"
                            >
                                全屏
                            </Button>
                        </Space>
                        <Button
                            onClick={togglePlayer}
                            type="text"
                            icon={<CloseOutlined />}
                            size="small"
                            className="close-btn"
                        />
                    </Space>
                }
            >
                {/* 海康多窗口播放器容器 */}
                <div id="multi_hik_camera_player" ref={playerContainerRef}></div>
            </Card>
        </Rnd>
    );

    return ReactDOM.createPortal(content, document.body);
};

export default GlobalHikCameraPlayer;
